package MyDaily.Servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import MyDaily.dao.user.UserQuery;
import MyDaily.dao.user.changeUserpassword;
import MyDaily.pojo.User;

/**
 * Servlet implementation class ForgetServlet
 */
@WebServlet("/ForgetServlet")
public class ForgetServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ForgetServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置请求和响应数据的字符集编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		// 获取页面信息
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String password = request.getParameter("password");
		String once = request.getParameter("oonce");
		// 判断数据库是否有用户输入的name和password
		// 调用查询方法
		UserQuery userQuery = new UserQuery();
		List<User> uList = userQuery.LoginQuery();
		System.out.println(uList.get(0).getPhone());
		for (int i = 0; i < uList.size(); i++) {
			if (uList.get(i).getName().equals(name) || uList.get(i).getPhone().equals(phone)) {// 判断是否有这个用户及手机是否真确
				// 判断用户输入的两次密码是否正确
				if (password.equals(once)) {
					// 调用修改方法
					changeUserpassword cUserpassword = new changeUserpassword();
					int row = cUserpassword.updatapassword(name, password);
					// 判断是否修改成功
					if (row > 0) {
						// 成功后转发到登录页面
						request.getRequestDispatcher("login.jsp").forward(request, response);
					} else {
						// 修改失败，向页面打印修改失败
						request.setAttribute("msg", "对不起，修改密码失败");
						request.getRequestDispatcher("forget.jsp").forward(request, response);
					}
				} else {
					// 两次密码不一致
					request.setAttribute("erro", "两次密码不一致");
					request.getRequestDispatcher("forget.jsp").forward(request, response);
				}
			} else {
				// 数据库没有此名称或号码
				request.setAttribute("null", "系统中没有该用户");
				request.getRequestDispatcher("forget.jsp").forward(request, response);
			}
		}

	}

}
